/*
   Copyright 2009 the original author or authors

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package com.googlecode.kohmori.springmvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import com.googlecode.kohmori.reportgen.JDBCConnObj;

import org.springframework.validation.BindException;

public class SimpleLoginReportController extends SimpleReportController
{
    private JDBCConnObj jdbcConnObj;    

    @Override
    protected Object formBackingObject(HttpServletRequest arg0) throws Exception {
        LoginReportParams form = (LoginReportParams) super.formBackingObject(arg0);
        form.setUsername("abc");
        form.setPassword("abc");
        form.setDatabaseName("toursdb");
        return form;        
    }

    @Override
    protected final void onBindAndValidate(HttpServletRequest request, Object object,
            BindException errors) throws Exception {
        if (!errors.hasErrors()) {
            HttpSession session = request.getSession(true);
            LoginReportParams form = (LoginReportParams) object;

            if (jdbcConnObj == null) {
               throw new IllegalStateException("(Internal error) Database " +
                       "connection is not set!");
            }

            try {
                jdbcConnObj.connectToDatabase(form.getUsername(), form.getPassword(),
                        form.getDatabaseName());
                session.setAttribute("connection", jdbcConnObj.getDBConn());
            } catch (IllegalStateException ex) {
                // "xxxxx" is to force use of fallback message (third argument)
                errors.rejectValue("username", "xxxxx", ex.getMessage());
            }
        }
    }    
    
    /**
     * Setter for property jdbcConnObj.
     * @param jdbcConnObj New value of property jdbcConnObj.
     */
    public void setJdbcConnObj(JDBCConnObj jdbcConnObj) {
        this.jdbcConnObj = jdbcConnObj;
    }
    
}
